<?php

require_once 'libraries/PHPMailerAutoload.php';
require_once 'config/smptConfig.php';
require_once 'config/db.php';

function createSurveyAndInvite() {
	date_default_timezone_set('Etc/UTC');
	
	$toAddresses = $_POST['invitees'];
	$toAddressesArr = explode(',',$toAddresses);
	foreach ($toAddressesArr as &$valueTo) {
		$valueTo = trim($valueTo);
	}
	unset($valueTo);

	$con=mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
	// Check connection
	if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}
	
	$sql = 'INSERT INTO survey(survey_name, creator_name, length, status) VALUES("'.$_POST['eventName'].'","'.$_POST['creatorName'].'", "'.$_POST['eventLength'].'", "Open")';
	if (!mysqli_query($con, $sql)) {
       	echo "Error: " . $sql . "<br>" . mysqli_error($con);
	}

	$sql = 'SELECT MAX(survey_id) FROM survey';
	$result = mysqli_query($con,$sql);
	$row = mysqli_fetch_array($result);
	$surveyId = $row[0];
	
	mysqli_close($con);
	
	
	$Subject = $_POST['creatorName'].' invited you to fill availability survey';
	
	$Message = 'Hey,<br/>'.$_POST['creatorName'].' asked you to fill your availability during week for '.$_POST['eventLength'].'h long event: '.$_POST['eventName'].'.<br/>To fill the form click <a href=localhost/scheduler/fillsurvey.php?survey='.$surveyId.'>here</a>';
	
	$mail = new PHPMailer;
	
	//Tell PHPMailer to use SMTP
	$mail->isSMTP();
	$mail->isHTML(true);
	//Enable SMTP debugging
	// 0 = off (for production use)
	// 1 = client messages
	// 2 = client and server messages
	$mail->SMTPDebug = 0;
	
	//Ask for HTML-friendly debug output
	$mail->Debugoutput = 'html';
	
	//Set the hostname of the mail server
	$mail->Host = SMTP_HOST;
	
	//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
	$mail->Port = 587;
	
	//Set the encryption system to use - ssl (deprecated) or tls
	$mail->SMTPSecure = 'tls';
	
	//Whether to use SMTP authentication
	$mail->SMTPAuth = true;
	
	//Username to use for SMTP authentication - use full email address for gmail
	$mail->Username = MAIL_SENDER;
	
	//Password to use for SMTP authentication
	$mail->Password = MAIL_PASS;
	
	//Set who the message is to be sent from
	$mail->setFrom('your email', 'Your name');
	
	if (!empty($toAddressesArr)) {
		foreach ($toAddressesArr as $value) {
			$mail->addAddress($value);
			}
	}
		
	//Set the subject line
	$mail->Subject = $Subject;
	$mail->Body = $Message;

	if (!$mail->send()) {
		print '<script type="text/javascript">';
    	print 'alert("Error while sending message");';
		//print 'history.back();';
  		print '</script>';
	} else {
		$Subject = 'Your administration link to availability survey for '.$_POST['eventName'];
		
		$Message = 'Hey '.$_POST['creatorName'].',<br/> To fill your availability for '.$_POST['eventLength'].'h long event: '.$_POST['eventName'].' click <a href=localhost/scheduler/fillsurvey.php?survey='.$surveyId.'>here</a>
				<br/> To view results of your survey click <a href=localhost/scheduler/fillsurvey.php?survey='.$surveyId.'&admin=y>here</a>';
		$mail->clearAddresses();
		$mail->Subject = $Subject;
		$mail->Body = $Message;
		$mail->addAddress($_POST['creatorEmail']);
		if ($mail->send()) {
			print '<script type="text/javascript">';
    		print 'alert("Your survey is created and your friends got invitations to fill it!");';
  			print '</script>';
  			header('Location: fillsurvey.php?survey='.$surveyId);
		}
	}
}

if (isset($_POST['submitButton'])) {
	createSurveyAndInvite();
}
